package app.kotlin_1.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Shader

import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

/**
 * Created by 刘智强 on 2017/9/21.
 */

object ImageUtil {
    fun getReverseBitmapById(bitmap: Bitmap?, context: Context): Bitmap? {
        //        Bitmap sourceBitmap= BitmapFactory.decodeResource(context.getResources(),resId);
        if (bitmap == null) return null
//绘制原图的下一半图片
        val matrix = Matrix()
        //倒影翻转
        matrix.setScale(1f, -1f)

        val inverseBitmap = Bitmap.createBitmap(bitmap, 0, bitmap.height / 2, bitmap.width, bitmap.height / 3, matrix, false)
        //合成图片
        val groupbBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height + bitmap.height / 3 + 60, bitmap.config)
        //以合成图片为画布
        val gCanvas = Canvas(groupbBitmap)
        //将原图和倒影图片画在合成图片上
        gCanvas.drawBitmap(bitmap, 0f, 0f, null)
        gCanvas.drawBitmap(inverseBitmap, 0f, (bitmap.height + 50).toFloat(), null)
        //添加遮罩
        val paint = Paint()
        val tileMode = Shader.TileMode.CLAMP
        val shader = LinearGradient(0f, (bitmap.height + 50).toFloat(), 0f,
                groupbBitmap.height.toFloat(), Color.BLACK, Color.TRANSPARENT, tileMode)
        paint.shader = shader
        //这里取矩形渐变区和图片的交集
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN)
        gCanvas.drawRect(0f, (bitmap.height + 50).toFloat(), bitmap.width.toFloat(), groupbBitmap.height.toFloat(), paint)
        return groupbBitmap
    }

    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    fun returnBitmap(url: String): Bitmap? {
        var fileUrl: URL? = null
        var bitmap: Bitmap? = null

        try {
            fileUrl = URL(url)
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        }

        try {
            val conn = fileUrl!!.openConnection() as HttpURLConnection
            conn.doInput = true
            conn.connect()
            val `is` = conn.inputStream
            bitmap = BitmapFactory.decodeStream(`is`)
            `is`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return bitmap

    }
}
